﻿Imports System
Imports System.Data
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Data.SqlClient
Public Class ManageDownload

    Inherits System.Web.UI.Page
    Dim connStr As String = ConfigurationManager.ConnectionStrings("yafnet").ConnectionString
    Dim filepath As String
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        filepath = Server.MapPath("../Downloads/")
        If IsPostBack Then


        Else

            Select Case Request.Params("Action")
                Case "View"
                    SqlDataSource2.SelectCommand = "SELECT yaf_User.Avatar, Files.FileID, Files.Name, Files.FileName, Files.FileImage, yaf_User.Name AS Expr2, yaf_User.DisplayName, yaf_User.Joined, yaf_User.LastVisit, yaf_User.Suspended, yaf_User.Email, yaf_User.IP, yaf_User.NumPosts, COUNT(Downloads.Userid) AS Totaldownloads FROM Files INNER JOIN Downloads ON Files.FileID = Downloads.FileID INNER JOIN yaf_User ON Downloads.Userid = yaf_User.UserID GROUP BY yaf_User.Avatar, Files.FileID, Files.Name, Files.FileName, Files.FileImage, yaf_User.Name, yaf_User.DisplayName, yaf_User.Joined, yaf_User.LastVisit, yaf_User.Suspended, yaf_User.Email, yaf_User.IP, yaf_User.NumPosts, Downloads.Userid HAVING (Files.FileID = '" & Request.Params("FileID") & "' ) ORDER BY yaf_User.DisplayName"

                

        ViewDownloads.Visible = True


                Case "New"
        UploadFile.Visible = True
        AddDownload.Visible = True

                Case "Delete"
                    deletediv.Visible = True
                Case "Edit"
        UploadFile.Visible = True
        AddDownload.Visible = True
            End Select


        End If
    End Sub

    Protected Sub listdownloads()


    End Sub











    Protected Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As RepeaterItemEventArgs)
        If YafContext.Current.IsAdmin = True Then
            Try
                Dim mydiv As HtmlGenericControl = CType(e.Item.FindControl("UserIP"), HtmlGenericControl)
                mydiv.Visible = True
            Catch ex As Exception
            End Try

        End If
        If Repeater1.Items.Count < 1 Then


            If e.Item.ItemType = ListItemType.Footer Then


                Dim StatusMessage As Label = CType(e.Item.FindControl("StatusLabel"), Label)
                StatusMessage.Text = "There are no items to display"
                StatusMessage.Visible = True
            End If
        End If
    End Sub



    Protected Sub DeleteDownload(DownloadID As String)

        If YafContext.Current.IsAdmin = False Then
            Label1.Text = "Restricted Area." & vbCrLf & " You do not have permissions to remove files!"
            Exit Sub
        End If
        Try
            Dim FileToDelete As String

            FileToDelete = filepath & Getfile(DownloadID)

            If System.IO.File.Exists(FileToDelete) = True Then

                System.IO.File.Delete(FileToDelete)
                MsgBox("File Deleted")

            End If

            Dim connStr As String = ConfigurationManager.ConnectionStrings("xwinnConnectionString").ConnectionString
            Dim dcon As New Data.SqlClient.SqlConnection
            Dim dquery As New Data.SqlClient.SqlCommand
            dcon.ConnectionString = connStr
            dquery.Connection = dcon
            'Select Query here
            dquery.CommandText = "DELETE FROM Files WHERE        (FileID = '" & DownloadID & "')"
            dcon.Open()
            dquery.ExecuteNonQuery()

            Response.Redirect("../Download.aspx", True)
        Catch ex As Exception
        End Try
        Response.Redirect("../Download.aspx", True)
    End Sub
    Protected Sub btnAddImage_Click(ByVal sender As Object, ByVal e As EventArgs)
        If FileUpload1.HasFile Then
            'if file uploaded
            If checkFileType(FileUpload1.FileName) Then
                'Check for file types
                Try
                    'save file
                    FileUpload1.SaveAs(MapPath("~/Downloads/" & FileUpload1.FileName))
                    System.Threading.Thread.Sleep(8000)
                    Label1.Text = "Upload successfull!"
                    Label1.ForeColor = Drawing.Color.LimeGreen
                Catch generatedExceptionName As System.IO.DirectoryNotFoundException
                    createDir()
                Catch ex As Exception
                    Label1.Text = ex.Message
                    Label1.ForeColor = Drawing.Color.Red
                End Try
            End If
        Else
            Label1.Text = "Invalid File Format, You may not upload that type of file!"
            Label1.ForeColor = Drawing.Color.Red
        End If
    End Sub
    Private Function checkFileType(ByVal fileName As String) As Boolean
        Dim fileExt As String = Path.GetExtension(FileUpload1.FileName)
        'TODO: Add Editable File Extension Restrictions in Settings
        Select Case fileExt.ToLower()
            Case ".zip"
                Return True
            Case ".rar"
                Return True
            Case ".cab"
                Return True
            Case Else
                Return True

        End Select
    End Function
    Private Sub createDir()
        Dim myDir As New DirectoryInfo(MapPath("~/Downloads/"))
        myDir.Create()

        'Now save file
        FileUpload1.SaveAs(MapPath("~/Downloads/" & FileUpload1.FileName))

    End Sub
    Private Sub Updatepermissions(fileid As String)

        Dim item As ListItem
        Dim dcon As New Data.SqlClient.SqlConnection
        Dim dquery As New Data.SqlClient.SqlCommand
        dcon.ConnectionString = connStr
        dquery.Connection = dcon
        dcon.Open()
        For Each item In CheckBoxList1.Items

            'Select Query here
            If SqlExists("FileID", "FileAccess", "WHERE (RankID = '" & GetRank(item.Text) & "') AND (FileID = '" & fileid & "')") Then

                Dim rows As String
                dquery.CommandText = "UPDATE    FileAccess  SET CanAccess ='" & item.Selected & "' WHERE (RankID = '" & GetRank(item.Text) & "') AND (FileID = '" & fileid & "')"
                rows = dquery.ExecuteNonQuery()
                Dim i As Integer


            Else


                dquery.CommandText = "INSERT INTO FileAccess   (FileID, RankID, CanAccess) VALUES        ('" & fileid & "','" & GetRank(item.Text) & "','" & item.Selected & "')"
                dquery.ExecuteNonQuery()

            End If




        Next

        dcon.Close()
    End Sub
    Private Sub LoadRanks()

        CheckBoxList1.Items.Clear()

        Dim dcon As New Data.SqlClient.SqlConnection
        Dim dquery As New Data.SqlClient.SqlCommand
        dcon.ConnectionString = connStr
        dquery.Connection = dcon
        'Select Query here
        dquery.CommandText = "SELECT        Name, RankID FROM            yaf_Rank ORDER BY Name"
        dcon.Open()
        Dim reader As Data.SqlClient.SqlDataReader = dquery.ExecuteReader
        While reader.Read
            Select Case reader("Name").ToString
                Case "Administration"

                Case Else
                    CheckBoxList1.Items.Add(reader("Name").ToString)
            End Select



        End While
        dcon.Close()




    End Sub
    Protected Function SqlExists(ByVal selectstring As String, ByVal fromstring As String, ByVal Value As String) As Boolean
        SqlExists = False
        Dim i As Integer = 0
        Try

            Dim dcon As New Data.SqlClient.SqlConnection
            Dim dquery As New Data.SqlClient.SqlCommand
            Dim password As String = ""
            dcon.ConnectionString = connStr
            dquery.Connection = dcon
            dquery.CommandText = "SELECT " & selectstring & " FROM " & fromstring & " " & Value
            dcon.Open()
            Dim reader As Data.SqlClient.SqlDataReader = dquery.ExecuteReader

            While reader.Read


                i = i + 1

            End While

            dcon.Close()

        Catch sex As SqlException
            MsgBox(sex.Message & " .sqlexists")
        Catch ex As Exception
            MsgBox(ex.Message & " .sqlexists")
        Finally
            If i = 0 Then
                SqlExists = False
            Else
                SqlExists = True

            End If
        End Try


    End Function
    Public Function GetRank(Rank As String) As String

        GetRank = ""
        Dim dcon As New SqlClient.SqlConnection
        Dim dquery As New SqlClient.SqlCommand

        dcon.ConnectionString = connStr
        dquery.Connection = dcon
        'Select Query here
        dquery.CommandText = "SELECT        Name, RankID  FROM            yaf_Rank WHERE  (Name = '" & Rank & "')"
        dcon.Open()
        Dim reader As SqlClient.SqlDataReader = dquery.ExecuteReader
        While reader.Read
            GetRank = reader("RankID")
        End While

        dcon.Close()

    End Function

    Public Function Getfile(Fileid As String) As String

        Getfile = ""
        Dim dcon As New SqlClient.SqlConnection
        Dim dquery As New SqlClient.SqlCommand

        dcon.ConnectionString = connStr
        dquery.Connection = dcon
        'Select Query here
        dquery.CommandText = "SELECT        FileName FROM            Files WHERE        (FileID = '" & Fileid & "')"
        dcon.Open()
        Dim reader As SqlClient.SqlDataReader = dquery.ExecuteReader
        While reader.Read
            Getfile = reader("Filename")
        End While

        dcon.Close()

    End Function

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        DeleteDownload(Request.Params("FileID"))
    End Sub
End Class
